<template>
  <div class="app-container">
    <header>
      <h1>中国象棋</h1>
      <div class="connection-status" :class="{ 'connected': connectionStatus === '已连接到MQTT服务器' || connectionStatus === '准备就绪' }">
        服务器状态: {{ connectionStatus }}
      </div>
      <button class="back-button" @click="router.push('/')">返回首页</button>
    </header>

    <div class="user-profile-bar">
      <div class="user-avatar" :style="{ backgroundColor: getUserColor(userService.userId.value) }">
        {{ userService.username.value.substring(0, 1) }}
      </div>
      <div class="user-info">
        <div class="username">{{ userService.username.value }}</div>
        <div class="user-id">用户ID: {{ userService.userId.value }}</div>
      </div>
      <div class="game-stats">
        <div class="stat-item">
          <div class="stat-label">状态</div>
          <div class="stat-value" :class="getStatusClass(chessGameService.status.value)">{{ getStatusText(chessGameService.status.value) }}</div>
        </div>
      </div>
    </div>

    <main>
      <div class="game-container">
        <div class="game-board">
          <ChessPanel />
        </div>
      </div>
    </main>


    <footer>
      <p>© {{ new Date().getFullYear() }} 中国象棋 - MQTT实时对战</p>
      <p class="server-info">MQTT服务器: kf9d2a91.ala.cn-hangzhou.emqxsl.cn</p>
    </footer>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import { useRouter } from 'vue-router';
import ChessPanel from '@/games/chess/components/ChessPanel.vue';
import { chessGameService } from '@/games/chess/services/ChessGameService';
import { initChessMessageHandler } from '@/games/chess/services/ChessMessageHandler';
import { mqttService } from '@/games/chess/services/MQTTService';
import { userService } from '@/games/chess/services/UserService';

const router = useRouter();

const connectionStatus = ref('初始化中...');

onMounted(async () => {
  try {
    connectionStatus.value = '正在连接MQTT服务器...';
    if (!mqttService.connected.value) {
      await mqttService.connect();
    }
    connectionStatus.value = '已连接到MQTT服务器';
    if (!userService.isLoggedIn.value) {
      const guestId = 'guest_' + Math.floor(Math.random() * 10000);
      userService.setUserId(guestId);
      userService.setUsername('访客' + guestId.substring(6));
    }
    chessGameService.init();
    setTimeout(() => {
      initChessMessageHandler();
      connectionStatus.value = '准备就绪';
    }, 1000);
  } catch (error) {
    connectionStatus.value = '连接失败: ' + error.message;
  }
});

onBeforeUnmount(() => {
  mqttService.unsubscribeAll();
  chessGameService.startNewGame();
});

function getUserColor(userId) {
  let hash = 0;
  for (let i = 0; i < userId.length; i++) {
    hash = userId.charCodeAt(i) + ((hash << 5) - hash);
  }
  const hue = Math.abs(hash % 360);
  return `hsl(${hue}, 70%, 60%)`;
}

function getStatusText(status) {
  switch (status) {
    case 'idle': return '空闲';
    case 'matching': return '匹配中';
    case 'playing': return '游戏中';
    case 'game_over': return '游戏结束';
    default: return '未知状态';
  }
}

function getStatusClass(status) {
  switch (status) {
    case 'idle': return 'status-idle';
    case 'matching': return 'status-matching';
    case 'playing': return 'status-playing';
    case 'game_over': return 'status-game-over';
    default: return '';
  }
}
</script>

<style scoped>
.app-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
header {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
}
header h1 {
  font-size: 32px;
  color: #2c3e50;
  margin-bottom: 5px;
}
.connection-status {
  font-size: 14px;
  color: #e74c3c;
  transition: color 0.3s;
}
.connection-status.connected {
  color: #2ecc71;
}
.user-profile-bar {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: white;
  font-weight: bold;
  margin-right: 15px;
}
.user-info {
  flex: 1;
}
.username {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}
.user-id {
  font-size: 14px;
  color: #666;
  word-break: break-all;
}
.game-stats {
  display: flex;
  margin-left: 20px;
}
.stat-item {
  text-align: center;
  margin-left: 20px;
}
.stat-label {
  font-size: 14px;
  color: #666;
}
.stat-value {
  font-size: 16px;
  font-weight: bold;
}
.status-idle { color: #666; }
.status-matching { color: #f39c12; }
.status-playing { color: #2ecc71; }
.status-game-over { color: #e74c3c; }
main {
  margin-bottom: 40px;
}
.game-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}
.game-board {
  flex: 1;
  min-width: 300px;
  display: flex;
  justify-content: center;
}
.game-sidebar {
  width: 100%;
  max-width: 400px;
}
footer {
  text-align: center;
  padding: 20px 0;
  color: #666;
  font-size: 14px;
  border-top: 1px solid #eee;
}
.server-info {
  font-size: 12px;
  margin-top: 5px;
  color: #999;
}
.back-button {
  position: absolute;
  right: 20px;
  top: 20px;
  padding: 10px 15px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}
.back-button:hover {
  background-color: #0056b3;
}
@media (max-width: 768px) {
  .game-container {
    flex-direction: column;
  }
  .game-sidebar {
    width: 100%;
    max-width: none;
  }
  .user-profile-bar {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  .user-avatar {
    margin-right: 0;
    margin-bottom: 10px;
  }
  .game-stats {
    margin-left: 0;
    margin-top: 10px;
  }
}
</style>